package com.msblearn.C_006;

import java.util.ArrayList;
import java.util.List;

/**
 * 第三种使用：await:
 * <p>
 * notifyAll()不释放锁。所以以下方法不行。
 */
public class T003_TestNotifyHoldingLock {
    //ArrayList是线程不安全的。
    volatile List list = new ArrayList();
//    volatile  List list = Collections.synchronizedList(new LinkedList<>());

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        T003_TestNotifyHoldingLock holdingLock = new T003_TestNotifyHoldingLock();
        final Object o = new Object();
        //先启动t2,在启动t1
        new Thread(() -> {
            synchronized (o) {
                System.out.println("T2启动");

                if (holdingLock.size() != 5) {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }, "T2").start();
        new Thread(() -> {
            System.out.println("t1启动");
            synchronized (o) {
                for (int i = 0; i < 10; i++) {
                    holdingLock.add("add" + i);
                    System.out.println("add" + i);
                    if (holdingLock.size() == 5) {
                        o.notifyAll();
                    }

                }
            }

        }, "t1").start();


    }
}
